package libs

import (
	"errors"
	"github.com/gin-gonic/gin"
)

// BindRequestParam 绑定参数校验参数
func BindRequestParam(ctx *gin.Context, data interface{}) (err error) {
	//绑定参数
	if ctx.Request.Method == "POST" {
		contentType := ctx.ContentType()
		if contentType == "application/json" {
			err = ctx.ShouldBindJSON(data)
		} else {
			err = ctx.ShouldBind(data)
		}
	} else {
		err = ctx.ShouldBind(data)
	}
	//校验参数
	if err != nil {
		if cErr := CheckRequest(err); cErr != "" {
			return errors.New(cErr)
		}
	}
	return nil
}

// GetRequestParams get请求参数
func GetRequestParams(ctx *gin.Context, data interface{}) (err error) {
	if err = ctx.ShouldBind(data); err != nil {
		if cErr := CheckRequest(err); cErr != "" {
			return errors.New(cErr)
		}
	}
	return err
}

// PostRequestParams post请求参数
func PostRequestParams(ctx *gin.Context, data interface{}) (err error) {
	contentType := ctx.ContentType()
	if contentType == "application/json" {
		err = ctx.ShouldBindJSON(data)
	} else {
		err = ctx.ShouldBind(data)
	}
	if cErr := CheckRequest(err); cErr != "" {
		return errors.New(cErr)
	}
	return err
}
